import 'dart:io';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:winkai/helper/router_helper.dart';
import 'package:winkai/helper/value_helper.dart';
import 'package:winkai/res/app_colors.dart';
import 'package:winkai/route/route_manifest.dart';
import 'package:winkai/translation/translation.dart';
import 'package:winkai/utils/context_utils.dart';
import 'package:winkai/utils/smart_dialog.dart';

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  DateTime? lastTime;

  @override
  void initState() {
    super.initState();
    init();
  }

  void init() {
    if (Platform.isAndroid) {
      SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(statusBarColor: Colors.transparent),
      );
    }
    initEasyRefresh();
  }

  void initEasyRefresh() {
    EasyRefresh.defaultHeaderBuilder = () => CupertinoHeader(
          triggerOffset: 30,
          backgroundColor: Colors.white,
          foregroundColor: AppColors.black1a.withOpacity(0.6),
        );
    EasyRefresh.defaultFooterBuilder = () => const MaterialFooter(
        backgroundColor: Colors.white,
        valueColor: AlwaysStoppedAnimation<Color>(AppColors.mainColor));
    // EasyRefresh.defaultHeaderBuilder = () => const CupertinoHeader();
    // EasyRefresh.defaultFooterBuilder = () => const CupertinoFooter();
  }

  @override
  Widget build(BuildContext context) {
    ///获取语言选择缓存
    var defaultTextStyle = const TextStyle(color: Colors.black);
    var defaultLocale = const Locale('en', 'US');
    var currentLanguage = ValueHelper.instance.languageInfo;
    Locale? systemLocal;
    String countryCode;
    String languageCode;
    if (currentLanguage == null ||
        currentLanguage.languageCode.isEmpty ||
        currentLanguage.countryCode.isEmpty) {
      List<String> languageCodeList = Platform.localeName.split("_");
      if (languageCodeList.contains("zh")) {
        countryCode = "CN";
        languageCode = "zh";
      } else {
        languageCode = "en";
        countryCode = "US";
      }
      systemLocal = Locale(languageCode, countryCode);
    } else {
      systemLocal = Locale(
        currentLanguage.languageCode,
        currentLanguage.countryCode,
      );
    }
    return ScreenUtilInit(
      designSize: const Size(375, 667),
      builder: (_, child) => WillPopScope(
        child: GetMaterialApp(
          navigatorKey: ContextUtils.navigatorKey,
          translations: Translation(),
          // 你的翻译
          locale: systemLocal ?? defaultLocale,
          // 将会按照此处指定的语言翻译
          fallbackLocale: defaultLocale,
          // 添加一个回调语言选项，以备上面指定的语言翻译不存在
          title: 'Wink AI',
          theme: ThemeData(
            scaffoldBackgroundColor: AppColors.mainBackgroundColor,
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            canvasColor: Colors.transparent,
            brightness: Brightness.dark,
            bottomSheetTheme:
                const BottomSheetThemeData(backgroundColor: Colors.transparent),
            tabBarTheme: TabBarTheme(
              dividerHeight: 0,
              overlayColor: MaterialStateProperty.resolveWith((states) {
                return Colors.transparent;
              }),
              tabAlignment: TabAlignment.center,
            ),
            colorScheme: ColorScheme.fromSeed(
              seedColor: AppColors.mainBackgroundColor,
              primary: Colors.black,
              brightness: Brightness.dark,
              surfaceTint: Colors.transparent,
            ),
            textTheme: TextTheme(
              displayLarge: defaultTextStyle,
              displayMedium: defaultTextStyle,
              displaySmall: defaultTextStyle,
              headlineLarge: defaultTextStyle,
              headlineMedium: defaultTextStyle,
              headlineSmall: defaultTextStyle,
              titleLarge: defaultTextStyle,
              titleMedium: defaultTextStyle,
              titleSmall: defaultTextStyle,
              bodyLarge: defaultTextStyle,
              bodyMedium: defaultTextStyle,
              bodySmall: defaultTextStyle,
              labelLarge: defaultTextStyle,
              labelMedium: defaultTextStyle,
              labelSmall: defaultTextStyle,
            ),
            appBarTheme: const AppBarTheme(
              color: Colors.white,
              elevation: 0.0,
              scrolledUnderElevation: 0,
            ),
            bottomAppBarTheme: const BottomAppBarTheme(color: Colors.white),
          ),
          routingCallback: (r) {},
          supportedLocales: const [
            Locale('zh', 'CN'),
            Locale('zh', 'TW'),
            Locale('en', 'US'), // 美国英语
          ],
          navigatorObservers: [
            FlutterSmartDialog.observer,
            RouterHelper().observer,
          ],
          builder: FlutterSmartDialog.init(builder: (ctx, child) {
            return MediaQuery(
              data: MediaQuery.of(ctx)
                  .copyWith(textScaler: const TextScaler.linear(1.0)),
              child: GestureDetector(
                onTap: () {
                  FocusScopeNode focus = FocusScope.of(ctx);
                  if (!focus.hasPrimaryFocus && focus.focusedChild != null) {
                    FocusManager.instance.primaryFocus!.unfocus();
                  }
                },
                child: child,
              ),
            );
          }),
          localeResolutionCallback: (deviceLocale, supportedLocales) {
            // var languageInfo = ValueHelper.instance.languageInfo;
            // if (deviceLocale.countryCode == "TW" &&
            //     deviceLocale.languageCode == "zh") {
            //   if (languageInfo == null) {
            //     Get.updateLocale(const Locale("zh", "TW"));
            //
            //     ValueHelper.instance.saveLanguage(LanguageInfo(
            //       languageCode: 'zh',
            //       countryCode: 'TW',
            //     ));
            //   }
            // } else if (deviceLocale.countryCode == "CN" &&
            //     deviceLocale.languageCode == "zh") {
            //   if (languageInfo == null) {
            //     Get.updateLocale(const Locale("zh", "CN"));
            //     ValueHelper.instance.saveLanguage(LanguageInfo(
            //       languageCode: 'zh',
            //       countryCode: 'CN',
            //     ));
            //   } else {}
            // } else {
            //   if (languageInfo == null) {
            //     Get.updateLocale(const Locale("en", "US"));
            //     ValueHelper.instance.saveLanguage(LanguageInfo(
            //       languageCode: 'en',
            //       countryCode: 'US',
            //     ));
            //   } else {}
            // }
          },
          debugShowCheckedModeBanner: false,
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          initialRoute: RouteManifest.initialRoute,
          getPages: RouteManifest.getPages,
        ),
        onWillPop: () async {
          if (lastTime == null ||
              DateTime.now().difference(lastTime!) >
                  const Duration(seconds: 1)) {
            lastTime = DateTime.now();
            toast("再次点击退出程序");
            return false;
          }
          // AppPlugin().exitProcess();
          return true;
        },
      ),
    );
  }
}
